/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import controller.exceptions.NonexistentEntityException;
import controller.exceptions.RollbackFailureException;
import entidades.Promocao;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import entidades.Cardapio;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.transaction.UserTransaction;

/**
 *
 * @author Renato
 */
public class PromocaoJpaController {
    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "restaurantePU")
    private EntityManagerFactory emf = null;

    private Integer id;
    private Date validade;
    private String descricao;
    private List<Cardapio> cardapioCollection;
    public Promocao promocao;
    public Integer idSelecionado;

    public String novoPromocao(){
        this.promocao = new Promocao();
        return "novoPromocao";
    }

    public String listarPromocao(){
        return "listarPromocao";
    }

    public String excluirPromocao() throws NonexistentEntityException, RollbackFailureException, Exception{
        promocao = findPromocao(idSelecionado);
        destroy(idSelecionado);
        return "listarPromocao";
    }

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public String create() throws RollbackFailureException, Exception {
        if (promocao.getCardapioCollection() == null) {
            promocao.setCardapioCollection((List<Cardapio>) (Set<Cardapio>) new HashSet<Cardapio>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            em.getTransaction().begin();
            List<Cardapio> attachedCardapioCollection = new ArrayList<Cardapio>();
            for (Cardapio cardapioCollectionCardapioToAttach : promocao.getCardapioCollection()) {
                 cardapioCollectionCardapioToAttach = em.getReference(cardapioCollectionCardapioToAttach.getClass(), cardapioCollectionCardapioToAttach.getId());
                attachedCardapioCollection.add(cardapioCollectionCardapioToAttach);
            }
            promocao.setCardapioCollection(attachedCardapioCollection);
            em.persist(promocao);
            for (Cardapio cardapioCollectionCardapio : promocao.getCardapioCollection()) {
                cardapioCollectionCardapio.getPromocaoCollection().add(promocao);
                cardapioCollectionCardapio = em.merge(cardapioCollectionCardapio);
            }
            utx.commit();
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
        FacesMessage fm = new FacesMessage("Promoção '"+promocao.getId()+"' inserida");
        FacesContext.getCurrentInstance().addMessage("Promoção inserida", fm);
        return "listarPromocao";
    }

    public void edit(Promocao promocao) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            em.getTransaction().begin();
            Promocao persistentPromocao = em.find(Promocao.class, promocao.getId());
            Collection<Cardapio> cardapioCollectionOld = persistentPromocao.getCardapioCollection();
            Collection<Cardapio> cardapioCollectionNew = promocao.getCardapioCollection();
            List<Cardapio> attachedCardapioCollectionNew =  new ArrayList<Cardapio>();
            for (Cardapio cardapioCollectionNewCardapioToAttach : cardapioCollectionNew) {
                cardapioCollectionNewCardapioToAttach = em.getReference(cardapioCollectionNewCardapioToAttach.getClass(), cardapioCollectionNewCardapioToAttach.getId());
                attachedCardapioCollectionNew.add(cardapioCollectionNewCardapioToAttach);
            }
            cardapioCollectionNew = (Set<Cardapio>) attachedCardapioCollectionNew;
            promocao.setCardapioCollection((List<Cardapio>) (Set<Cardapio>) cardapioCollectionNew);
            promocao = em.merge(promocao);
            for (Cardapio cardapioCollectionOldCardapio : cardapioCollectionOld) {
                if (!cardapioCollectionNew.contains(cardapioCollectionOldCardapio)) {
                    cardapioCollectionOldCardapio.getPromocaoCollection().remove(promocao);
                    cardapioCollectionOldCardapio = em.merge(cardapioCollectionOldCardapio);
                }
            }
            for (Cardapio cardapioCollectionNewCardapio : cardapioCollectionNew) {
                if (!cardapioCollectionOld.contains(cardapioCollectionNewCardapio)) {
                    cardapioCollectionNewCardapio.getPromocaoCollection().add(promocao);
                    cardapioCollectionNewCardapio = em.merge(cardapioCollectionNewCardapio);
                }
            }
            utx.commit();
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id1 = promocao.getId();
                if (findPromocao(id1) == null) {
                    throw new NonexistentEntityException("The promocao with id " + id1 + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            em.getTransaction().begin();
            Promocao promocao1;
            try {
                promocao1 = em.getReference(Promocao.class, id);
                promocao1.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The promocao with id " + id + " no longer exists.", enfe);
            }
            Collection<Cardapio> cardapioCollection1 = promocao1.getCardapioCollection();
            for (Cardapio cardapioCollectionCardapio : cardapioCollection1) {
                cardapioCollectionCardapio.getPromocaoCollection().remove(promocao1);
                cardapioCollectionCardapio = em.merge(cardapioCollectionCardapio);
            }
            em.remove(promocao1);
            utx.commit();
            em.getTransaction().commit();
            FacesMessage fm = new FacesMessage("Promoção '"+promocao1.getId()+"' Excluida");
            FacesContext.getCurrentInstance().addMessage("Promoção excluida", fm);
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Promocao> findPromocaoEntities() {
        return findPromocaoEntities(true, -1, -1);
    }

    public List<Promocao> getfindPromocaoEntities() {
        return findPromocaoEntities(true, -1, -1);
    }

    public List<Promocao> findPromocaoEntities(int maxResults, int firstResult) {
        return findPromocaoEntities(false, maxResults, firstResult);
    }

    private List<Promocao> findPromocaoEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Promocao as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Promocao findPromocao(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Promocao.class, id);
        } finally {
            em.close();
        }
    }

    public int getPromocaoCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Promocao as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    public Integer getIdSelecionado() {
        return idSelecionado;
    }

    public void setIdSelecionado(Integer idSelecionado) {
        this.idSelecionado = idSelecionado;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Date getValidade() {
        return validade;
    }

    public void setValidade(Date validade) {
        this.validade = validade;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

     public Promocao getPromocao() {
        return promocao;
    }

    public void setPromocao(Promocao promocao) {
        this.promocao = promocao;
    }

    public List<Cardapio> getCardapioCollection() {
        return cardapioCollection;
    }

    public void setCardapioCollection(List<Cardapio> cardapioCollection) {
        this.cardapioCollection = cardapioCollection;
    }

}
